<template>
	<u-upload :fileList="imgList" @afterRead="afterRead" @beforeRead="beforeRead" useBeforeRead @delete="deletePic" name="1" multiple :maxCount="maxCount"></u-upload>
</template>

<script>
import { uploadOssFiles } from '@/api/user.js';
export default {
	name: 'Upload',
	props: {
		img: {
			type: [String, Array]
			// required: true
		},
		fileList: {
			type: [Array],
			default: () => []
		},
		maxCount: {
			type: [Number, String],
			default: 3
		},
		ossType: {
			type: String,
			default: 'upload'
		}
	},
	data() {
		return {
			formData: {},
			action: '',
			imgList: []
		};
	},
	watch: {
		fileList: {
			handler(val) {
				val.map((value) => {
					// 首先检查内部是否已经添加过这张图片，因为外部绑定了一个对象给fileList的话(对象引用)，进行修改外部fileList时，
					// 会触发watch，导致重新把原来的图片再次添加到this.imgList
					// 数组的some方法意思是，只要数组元素有任意一个元素条件符合，就返回true，而另一个数组的every方法的意思是数组所有元素都符合条件才返回true
					let tmp = this.imgList.some((listVal) => {
						return listVal.url === value.url;
					});
					// 如果内部没有这张图片，则添加到内部
					!tmp && this.imgList.push({ url: value.url, status: 'success', message: '' });
				});
			},
			immediate: true
		}
	},
	methods: {
		beforeRead(val) {
			console.log('------------------------------');
		},
		//获取oss 配置信息
		getOssInfo() {
			return new Promise((resolve, reject) => {
				uploadOssFiles(this.ossType)
					.then((res) => {
						const { host, dir, filename, policy, accessId, signature } = res;
						this.action = host; // oss上传地址
						this.formData = {
							key: dir + filename, // oss上传文件名
							policy, // oss上传策略
							OSSAccessKeyId: accessId, // oss上传 accessKeyId
							signature // oss上传签名
						};
						resolve();
					})
					.catch((err) => {
						reject(err);
					});
			});
		},
		// 删除图片
		deletePic(event) {
			this.imgList.splice(event.index, 1);
		},
		// 新增图片
		async afterRead(event) {
			// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
			let lists = [].concat(event.file);
			let fileListLen = this.imgList.length;
			lists.map((item) => {
				this.imgList.push({
					...item,
					status: 'uploading',
					message: '上传中'
				});
			});
			for (let i = 0; i < lists.length; i++) {
				await this.getOssInfo();
				const result = await this.uploadFilePromise(lists[i].url);
				let item = this.imgList[fileListLen];
				this.imgList.splice(
					fileListLen,
					1,
					Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					})
				);
				fileListLen++;
			}
		},
		uploadFilePromise(url) {
			return new Promise((resolve, reject) => {
				let a = uni.uploadFile({
					url: this.action, // 仅为示例，非真实的接口地址
					filePath: url,
					name: 'file',
					formData: this.formData,
					success: (res) => {
						setTimeout(() => {
							resolve(this.action + '/' + this.formData.key);
						}, 1000);
					},
					fail: (err) => {
						console.log(err);
					}
				});
			});
		}
	}
};
</script>
